import { Component, OnInit } from '@angular/core';
import {
  UntypedFormBuilder,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';

import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

import { FeatureService } from 'src/app/share/service/feature.service';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';
import { NzMessageService } from 'ng-zorro-antd/message';
import * as _ from 'lodash';
import { TFeatures } from 'src/app/pages/types';
import { DataService } from '../../feature.dataservice';

@Component({
  selector: 'app-feature-tree',
  templateUrl: './feature-tree.component.html',
  styleUrls: ['./feature-tree.component.less'],
})
export class FeatureTreeComponent implements OnInit {
  featureForm: UntypedFormGroup;

  constructor(
    private fb: UntypedFormBuilder,
    private featureService: FeatureService,
    private message: NzMessageService,
    private store: DataService
  ) {
    this.featureForm = this.fb.group({
      feature: ['', [Validators.required]],
    });
  }

  ngOnInit(): void {
    // 左侧的树初始化了
    this.queryFeatureList();
  }
  // 是否处于编辑状态中
  isEditing = false;
  isLoading = false;

  features: TFeatures[] = [];
  featuresCache: TFeatures[] = [];
  // 当前选中的feature的下标
  selectedFeatureIdx: number = -1;

  onFeatureClick(idx: number) {
    this.selectedFeatureIdx = idx;
    const selectFeature = this.features[idx];
    this.store.currentFeature.next(selectFeature);
  }

  // 查询feature列表
  queryFeatureList() {
    this.featureService.getFeatures().subscribe((res) => {
      const { code, data } = res as RESPONSE_DATA<TFeatures[]>;
      if (code === RESPONSE_CODE.SUCCESS) {
        const _data = [
          {
            id: -1,
            feature: 'All',
            sort: 0,
          },
          ...data,
        ];
        this.features = _data;
        this.featuresCache = _data;
        if (data.length > 0) {
          // 默认选中第一个Feature
          this.onFeatureClick(0);
        }
      }
    });
  }

  // 拖拽排序
  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(
      this.featuresCache,
      event.previousIndex,
      event.currentIndex
    );
    this.featuresCache.map((_, idx) => {
      this.featuresCache[idx]['sort'] = idx + 1;
    });
  }

  // 编辑feature
  editFeature() {
    // console.log('进入编辑状态');
    this.featuresCache = [...this.features];
    this.isEditing = true;
  }
  // 编辑完毕后保存数据
  saveEdit() {
    //根据排序后的featureCache生成sort
    this.featureService
      .updateFeatureBatch(this.featuresCache)
      .subscribe((res) => {
        const { code } = res as RESPONSE_DATA;
        if (code === RESPONSE_CODE.SUCCESS) {
          this.features = [...this.featuresCache];
          this.isEditing = false;
        }
      });
  }

  // 新增弹窗是否可见
  isaddVisible: boolean = false;
  showAddModule() {
    this.isaddVisible = true;
  }
  handleCancel() {
    this.isaddVisible = false;
  }

  handleOk() {
    Object.values(this.featureForm.controls).forEach((control) => {
      if (control.invalid) {
        control.markAsDirty();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });
    if (this.featureForm.valid) {
      // 验证通过后, 拿数据请求后端接口, 新增feature
      const value = this.featureForm.value;
      this.isLoading = true;
      this.featureService.postFeature(value).subscribe((res) => {
        const { code, msg } = res as RESPONSE_DATA;
        if (code == RESPONSE_CODE.SUCCESS) {
          this.message.success('添加feature成功');
          this.queryFeatureList();
        } else {
          this.message.error(msg);
        }
        this.isLoading = false;
        this.isaddVisible = false;
      });
    }
  }

  deleteFeature(idx: number) {
    const feature = this.featuresCache[idx];
    // 先调用删除接口
    this.featureService.deleteFeature(feature.id).subscribe((res) => {
      const { code, msg } = res as RESPONSE_DATA;
      if (code == RESPONSE_CODE.SUCCESS) {
        this.message.success('删除feature成功');
        this.featuresCache.splice(idx, 1);
        this.features = [...this.featuresCache];
      } else {
        this.message.error(msg);
      }
    });
  }
}
